// ============ AI工具调度系统 - 统一入口 ============

// 导出核心 Store 和类型
export { 
  useAiToolsStore,
  orchestrateToolCalls,
  executeToolCall,
  executeToolCallsRound
} from './store';

export type {
  ToolDefinition,
  ToolExecutionRequest,
  ToolExecutionResult,
  ToolExecutionTask,
  ToolHandler,
  OrchestrationOptions,
  OrchestrationResult,
  ChatMessage,
  ToolCallResponse,
  ToolQueryFilter,
  ToolExecutionContext
} from './types';

// 导出工具函数
export {
  stableStringify,
  combineSignals,
  createTimeoutSignal,
  Semaphore,
  generateCacheKey,
  normalizePath,
  classifyError,
  validateToolCall,
  generateId
} from './utils';

// 导出内置工具
export { BUILTIN_CHAT_COMPLETE } from './builtin/chat';
export { 
  BUILTIN_WORKSPACE_SEARCH,
  BUILTIN_WORKSPACE_APPLY_EDITS 
} from './builtin/workspace';
export {
  BUILTIN_WRITE_FILE,
  BUILTIN_CREATE_DIRECTORY,
  BUILTIN_LIST_DIRECTORY,
  BUILTIN_MOVE_FILE,
  BUILTIN_SEARCH_FILES,
  BUILTIN_GET_FILE_INFO,
  BUILTIN_READ_FILE,
  BUILTIN_READ_MULTIPLE_FILES
} from './builtin/filesystem';

// ============ 初始化函数 ============

/**
 * 初始化 AI 工具系统 - 注册所有内置工具
 * 在应用启动时调用此函数来注册内置工具
 */
export async function initAiToolsStore(): Promise<void> {
  const { useAiToolsStore } = await import('./store');
  const store = useAiToolsStore();
  
  // 避免重复注册
  const registeredToolIds = new Set(store.registeredTools.map((t: any) => t.id));
  
  // 导入所有内置工具
  const builtinTools = [
    // 聊天工具
    () => import('./builtin/chat').then(m => m.BUILTIN_CHAT_COMPLETE),
    
    // 工作区工具
    () => import('./builtin/workspace').then(m => m.BUILTIN_WORKSPACE_SEARCH),
    () => import('./builtin/workspace').then(m => m.BUILTIN_WORKSPACE_APPLY_EDITS),
    
    // 文件系统工具
    () => import('./builtin/filesystem').then(m => m.BUILTIN_WRITE_FILE),
    () => import('./builtin/filesystem').then(m => m.BUILTIN_CREATE_DIRECTORY),
    () => import('./builtin/filesystem').then(m => m.BUILTIN_LIST_DIRECTORY),
    () => import('./builtin/filesystem').then(m => m.BUILTIN_MOVE_FILE),
    () => import('./builtin/filesystem').then(m => m.BUILTIN_SEARCH_FILES),
    () => import('./builtin/filesystem').then(m => m.BUILTIN_GET_FILE_INFO),
    () => import('./builtin/filesystem').then(m => m.BUILTIN_READ_FILE),
    () => import('./builtin/filesystem').then(m => m.BUILTIN_READ_MULTIPLE_FILES),
  ];
  
  // 注册工具
  try {
    const tools = await Promise.all(builtinTools.map(loader => loader()));
    for (const tool of tools) {
      if (!registeredToolIds.has(tool.id)) {
        store.registerTool(tool);
        console.log(`[AiTools] Registered tool: ${tool.id}`);
      }
    }
    console.log(`[AiTools] Initialization complete. Total tools: ${store.registeredTools.length}`);
  } catch (error) {
    console.error('[AiTools] Failed to initialize builtin tools:', error);
  }
}

/**
 * 简化的初始化函数（同步版本）
 * 如果需要立即注册所有工具，可以使用此函数
 */
export async function initAiToolsStoreSync(): Promise<void> {
  const { useAiToolsStore } = await import('./store');
  const store = useAiToolsStore();
  
  // 同步导入内置工具
  import('./builtin/chat').then(({ BUILTIN_CHAT_COMPLETE }) => {
    if (!store.getTool('chat.complete')) {
      store.registerTool(BUILTIN_CHAT_COMPLETE);
    }
  });
  
  import('./builtin/workspace').then(({ BUILTIN_WORKSPACE_SEARCH, BUILTIN_WORKSPACE_APPLY_EDITS }) => {
    if (!store.getTool('workspace.search')) {
      store.registerTool(BUILTIN_WORKSPACE_SEARCH);
    }
    if (!store.getTool('workspace.applyEdits')) {
      store.registerTool(BUILTIN_WORKSPACE_APPLY_EDITS);
    }
  });
  
  import('./builtin/filesystem').then((filesystem) => {
    const tools = [
      ['write_file', filesystem.BUILTIN_WRITE_FILE],
      ['create_directory', filesystem.BUILTIN_CREATE_DIRECTORY],
      ['list_directory', filesystem.BUILTIN_LIST_DIRECTORY],
      ['move_file', filesystem.BUILTIN_MOVE_FILE],
      ['search_files', filesystem.BUILTIN_SEARCH_FILES],
      ['get_file_info', filesystem.BUILTIN_GET_FILE_INFO],
      ['read_file', filesystem.BUILTIN_READ_FILE],
      ['read_multiple_files', filesystem.BUILTIN_READ_MULTIPLE_FILES],
    ];
    
    for (const [id, tool] of tools) {
      if (typeof id === 'string' && !store.getTool(id)) {
        store.registerTool(tool as any);
      }
    }
  });
}

/**
 * 获取所有工具的摘要信息
 */
export async function getToolsSummary(): Promise<{
  totalTools: number;
  categories: Record<string, number>;
  tags: Record<string, number>;
}> {
  const { useAiToolsStore } = await import('./store');
  const store = useAiToolsStore();
  const tools = store.registeredTools;
  
  const categories: Record<string, number> = {};
  const tags: Record<string, number> = {};
  
  for (const tool of tools) {
    // 统计分类
    const category = tool.metadata?.category || 'uncategorized';
    categories[category] = (categories[category] || 0) + 1;
    
    // 统计标签
    const toolTags = tool.metadata?.tags || [];
    for (const tag of toolTags) {
      tags[tag] = (tags[tag] || 0) + 1;
    }
  }
  
  return {
    totalTools: tools.length,
    categories,
    tags
  };
}

// ============ 向前兼容性 ============

/**
 * @deprecated 使用 initAiToolsStore() 替代
 * 为了保持向后兼容性而保留的旧函数名
 */
export const initAiToolsStoreCompat = initAiToolsStoreSync;